package com.test.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * BaseDao 的实现类，继承了HibernateDaoSupport,通过gethibernatetemplate()操作数据库
 * @author Administrator 2015-9-29
 *
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
	protected Class<T> clazz=null;
	public BaseDaoImpl(){
		//通过反射获得T的真实类型
		//system.out.println(pt)这里会得到class com.baoxi.BaseDao<T>。即获得具体的类型。
		ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
		this.clazz = (Class<T>)pt.getActualTypeArguments()[0];
		System.out.println("获得的T的真实类型为clazz:"+clazz);
	}
	public boolean add(T entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().save(entity);
		return true;
	}

	public boolean delete(Integer id) {
		// TODO Auto-generated method stub
		if(id == null){
			return false;
		}
		Object entity = getById(id);
		if(entity!=null){
			this.getHibernateTemplate().delete(entity);
		}
		return true;
	}

	public List<T> findAll() {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate()
		.find("from "+clazz.getSimpleName()+"");
	}

	public T getById(Integer id) {
		// TODO Auto-generated method stub
		if(id==null){
			return null;
		}else{
			return (T) getHibernateTemplate().get(clazz, id);
		}
	}

	public List<T> getByIds(Integer[] ids) {
		// TODO Auto-generated method stub
		if(ids==null||ids.length==0){
			return Collections.EMPTY_LIST;
		}
		Session session = this.getSession();
		List<T> list=null;
		try{
			list = session.createQuery("from "+clazz.getSimpleName()+" where id in (:ids)")
			.setParameterList("ids", ids).list();			
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}

	public boolean update(T entity) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(entity);
		return true;
	}

}
